package com.ipay.wechat.util;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.ipay.utils.RandomStringUtils;
import com.ipay.wechat.component.Wechat;
import net.sf.json.JSONObject;

@Component
public class AddWechatJSUtil {
	private static Logger logger=Logger.getLogger(AddWechatJSUtil.class);
	
	public static String addWeiXinSDK(String page, Wechat wechat,String ticket) {
		String nonceStr = RandomStringUtils.randomAlphanumeric(20);
		String timeStamp = String.valueOf(new Date().getTime() / 1000);
		String[] signParams = { "noncestr", "jsapi_ticket", "timestamp", "url" };
		String[] values = { nonceStr, ticket, timeStamp, page };
		Map<String, String> paramMap = new HashMap<String, String>();
		for (int i = 0; i < signParams.length; i++) {
			paramMap.put(signParams[i], values[i]);
		}
		Arrays.sort(signParams);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < signParams.length; i++) {
			sb.append(signParams[i] + "=" + paramMap.get(signParams[i]) + "&");
		}
		String signStr = sb.toString().substring(0, sb.toString().length() - 1);
		String signature = SignUtil.sha1Encode(signStr).toLowerCase();


		JSONObject jsonObject = new JSONObject();
		jsonObject.put("appId",wechat.getAppId());
		jsonObject.put("timeStamp", timeStamp);
		jsonObject.put("nonceStr", nonceStr);
		jsonObject.put("signature", signature);
		logger.info("验证微信接口==="+jsonObject.toString());

		return jsonObject.toString();
	}

}
